package com.oddpointcc.szpt.accounting.web;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.oddpointcc.szpt.accounting.utils.WebUtil;

@ControllerAdvice
public class GlobalExceptionHandler {

	private static final Logger LOG = LogManager.getLogger(GlobalExceptionHandler.class);

	public static final String DEFAULT_ERROR_VIEW = "errors";

	@ExceptionHandler(value = { Exception.class, RuntimeException.class })
	public Object defaultErrorHandler(HttpServletRequest request, Exception e) {
		String username = (String) request.getSession().getAttribute("userUsername");
		String remoteAddr = request.getRemoteAddr();// 请求的IP
		String requestUri = request.getRequestURI();// 请求的Uri
		String method = request.getMethod(); // 请求的方法类型(post/get)
		Map<String, String[]> params = request.getParameterMap(); // 请求提交的参数
		ObjectMapper objectMapper = new ObjectMapper();
		String paramJson = null;
		try {
			paramJson = objectMapper.writeValueAsString(params);
		} catch (JsonProcessingException ex) {
		}
		long code = System.currentTimeMillis();
		LOG.error("username:{} remoteAddr:{} requestUri:{} method:{} params:{} code:{} exception:{}", username,
				remoteAddr, requestUri, method, paramJson, code, e);
		LOG.error("code:" + code + " - " + e.getMessage(), e);
		e.printStackTrace();
		ModelAndView mav = null;
		if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
			mav = new ModelAndView(new MappingJackson2JsonView());
		} else {
			mav = new ModelAndView(DEFAULT_ERROR_VIEW);
		}
		mav.addObject("errorCode", HttpStatus.INTERNAL_SERVER_ERROR.value());
		mav.addObject("errorMsg", "服务器出错了，请联系管理员");
		mav.addObject("code", code);
		return mav;
	}

	@ExceptionHandler(AccessDeniedException.class)
	public Object accessDeniedErrorHandler(HttpServletRequest request, Exception e) {
		LOG.error("权限拦截 username:{} - requestURL:{}", WebUtil.getLoginUserUsername(), request.getRequestURL());
		ModelAndView mav = null;
		if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
			mav = new ModelAndView(new MappingJackson2JsonView());
		} else {
			mav = new ModelAndView(DEFAULT_ERROR_VIEW);
		}
		mav.addObject("errorCode", HttpStatus.FORBIDDEN.value());
		mav.addObject("errorMsg", "你没有权限访问");
		return mav;
	}

}